#include"TcpServ.h"

TcpServ::TcpServ(boost::asio::io_context& ioc)
	:ioc(ioc),
	m_acceptor(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 10000))
{
	std::cout << "create tcp serv success\n\n";
}


std::shared_ptr<TcpServ> TcpServ::create(boost::asio::io_context& ioc)
{
	return std::shared_ptr<TcpServ>(new TcpServ(ioc));
}

void TcpServ::startAccept()
{
	std::cout << "服务器启动，监听端口: 10000\n\n";

	std::shared_ptr<TcpConnect> tcpConnect = TcpConnect::create(ioc);
	m_acceptor.async_accept(tcpConnect->getSocket(),
		[self = shared_from_this(), tcpConnect](const boost::system::error_code& ec)
		{
			self->handleAccept(tcpConnect, ec);
		});
}

void TcpServ::handleAccept(std::shared_ptr<TcpConnect> tcpConnect,const boost::system::error_code& ec)
{
    if (!ec)
    {
        // 获取客户端地址
        auto remoteEp = tcpConnect->getSocket().remote_endpoint();
        std::cout << "接受新连接: "
            << remoteEp.address().to_string() << ":"
            << remoteEp.port() << std::endl<<std::endl;

        // 开始处理连接
        tcpConnect->start();
    }
    else
    {
        // 错误分类处理
        if (ec == boost::asio::error::operation_aborted) {
            std::cerr << "接受操作被取消: 服务器可能正在关闭" << std::endl<<std::endl;
            return;
        }

        std::cerr << "接受连接错误 [" << ec.value() << "]: "
            << ec.message() << std::endl<<std::endl;
    }

    // 继续接受下一个连接
    if (m_acceptor.is_open())
    {
        startAccept();
    }
}